<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/10/30
 * Time: 11:37
 */

namespace app\api\controller\user;


use app\api\controller\BasicApi;
use Firebase\JWT\JWT;
use service\MemberService;
use service\WechatService;
use think\Db;
use think\Exception;

class Login extends BasicApi
{
    /**
     * 用户微信登录
     * @return \think\response\Json
     * @throws \WeChat\Exceptions\InvalidDecryptException
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function wx_login(){
        $code = $this->request->post('code');
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $parent_id = $this->request->post('parent_id',0);
        $data = WechatService::WeMiniCrypt()->userInfo($code, $iv, $encryptedData);
        if (!$data) {
            return json(['msg'=>'解密数据失败'],500);
        }
        $openid = isset($data['unionId']) ? $data['unionId'] : $data['openId'];
        $user=Db::name('store_member')->where('openid',$openid)->find();
        $udata['nickname']=$data['nickName'];
        $udata['sex']=$data['gender']==1?'男':'女';
        if(!empty($user['id'])){
            $udata['id']=$user['id'];
            Db::name('store_member')->update($udata);
        }else{
            $udata['openid']=$openid;
            $udata['headimg']=$data['avatarUrl'];
            $udata['create_at']=time();
            $udata['type']=MemberService::MEMBER_TYPE_NORMAL;
            $udata['parent_id']=$parent_id;
            $udata['status']=1;
            $udata['id']=Db::name('store_member')->insertGetId($udata);
        }
        $token_data = array(
            "iss" => "cqxueao.cn",
            "uid" => $udata['id'],
            "exp"=>time()+7200
        );
        $token=JWT::encode($token_data,config('jwt_key'));
        $return_data['token']=$token;
        $return_data['exp']=$token_data['exp'];
        return json(['msg'=>'登录成功','data'=>$return_data]);
    }

}